/**
 * 实现lua环境timer的使用  时间精度不大准确  凑合用了
 */
export default  class LuaTimer{


   // private static mainThreadRunFlag=false;

    private static defaultMainThreadMaxRunTimes=-1;

    private  mainThreadMaxRunTimes=0;

    private runFlag=true;

    private callback:Function;
    constructor(callback:Function){
        this.callback=callback;
    }
    public  runTimer(intervalMillSec:number,iMainThreadMaxRunTimes?:number){
        if(iMainThreadMaxRunTimes!=undefined){
            this.mainThreadMaxRunTimes=iMainThreadMaxRunTimes
        }else{
            this.mainThreadMaxRunTimes=LuaTimer.defaultMainThreadMaxRunTimes
        }

        let cbFunc=this.callback
        let co = coroutine.create(() =>{
            while(this.runFlag){
                cbFunc()
                //console.log('os time',os.time())
                coroutine.yield()
            }
        })
        //coroutine.resume(co) 
        // let lasted_time_msec = this.getMillis()
        // console.log('lasted_time_msec',lasted_time_msec)
        // console.log('lasted_time_msec',lasted_time_msec)
        // console.log('lasted_time_msec',lasted_time_msec)

        // if(!LuaTimer.mainThreadRunFlag){
        //     LuaTimer.mainThreadRunFlag=true
        //保持守护线程持续挂起
        let so=coroutine.create(() =>{
            let lasted_time_msec = this.getMillis()
            while(this.runFlag && ( this.mainThreadMaxRunTimes>0 || this.mainThreadMaxRunTimes==-1)){
                let cur_time_msec=this.getMillis()
                //if( os.difftime(cur_time_msec, lasted_time)>1 ){
                if( (cur_time_msec-lasted_time_msec)>intervalMillSec ){
                    if( this.mainThreadMaxRunTimes!=-1){
                        this.mainThreadMaxRunTimes=this.mainThreadMaxRunTimes-1
                    }
                    lasted_time_msec=cur_time_msec
                    coroutine.resume(co) 
                }
            }
            console.log('lua timer 跳出循环！！！')
        })
        coroutine.resume(so)   
        
    }

    public  destroyTimer(){
        this.runFlag=false
    }

    private getMillis(){
        // let now = os.time()
        // let ms = (os.clock() - os.time()) * 1000
        // return now * 1000 + math.floor(ms)
       return os.time() * 1000 + math.floor(os.clock() * 1000)
    }
       
    


}